package com.ttbj.product.api.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import com.ttbj.error.po.Error;
import com.ttbj.order.component.OrderComponent;
import com.ttbj.pay.dao.PayMapper;
import com.ttbj.pay.po.Pay;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.ttbj.core.util.QRUtil;
import com.ttbj.dispatch.dao.DispatchMapper;
import com.ttbj.dispatch.po.Dispatch;
import com.ttbj.error.component.ErrorComponent;
import com.ttbj.error.dao.ErrorMapper;
import com.ttbj.payment.original.service.OriginalPayService;
import com.ttbj.product.api.OrderFacade;
import com.ttbj.product.api.OriginalPayFacade;
import com.ttbj.product.api.WaybillFacade;
import com.ttbj.product.bean.dto.OrderDto;
import com.ttbj.timer.po.AchievedOrder;
import com.ttbj.timer.service.achieved.AchievedService;
import com.ttbj.util.Assert;
import com.ttbj.util.DateUtils;


@Service("originalPayFacade")
public class OriginalPayFacadeImpl implements OriginalPayFacade {
	private static final Logger log = LoggerFactory.getLogger(OriginalPayFacadeImpl.class);
	
	@Autowired
	OriginalPayService originalPayService = null;

	@Autowired
	ThreadPoolTaskExecutor taskExecutor = null;

	@Autowired
	ErrorMapper errorMapper = null;

	@Autowired
	WaybillFacade waybillFacade = null;

	@Autowired
	OrderFacade orderFacade = null;

	@Autowired
	PayMapper payMapper = null;

	@Autowired
	ErrorComponent errorComponent = null;

	@Autowired
	DispatchMapper dispatchMapper = null;

	@Autowired
	OrderComponent orderComponent = null;

	@Autowired
	AchievedService achievedService = null;

	/**
	 * 1.获取支付码 2.获取url
	 */
	private String appPayProcess(String rootPath, String imagePath, String url, Float price, String orderNum, String orderId, Integer payType) throws Exception {
		String content = null;
		String urlhead = null;
		switch (payType) { // 支付类型 0. 微信 1.支付宝 3.银行卡
		case 0:
			content = originalPayService.wxPayNative(url, price, null, orderId);
			urlhead = "wxQrCode";
			break;
		case 1:
			content = originalPayService.aliPayNative(url, price, null, orderId);
			urlhead = "aliQrCode";
			break;
		default:
			break;
		}
		Assert.assertNonNullObj(content, 232, "预下单失败");
		String imageName = QRUtil.encode(content, null, rootPath + imagePath, false, true, urlhead + System.currentTimeMillis());
		return url + imagePath + imageName;
	}

	@Override
	public Map<String, String> appletPay(String url, Float price, String orderNum, String openId, String orderId) throws Exception {
		return originalPayService.wxPayJSAPI(url, price, orderNum, openId, orderId);
	}

	@Override
	public Map<String, String> appPay(String rootPath, String imagePath, String url, Float price, String orderNum, String orderId) throws Exception {
		Future<String> aliFuture = taskExecutor.submit(() -> appPayProcess(rootPath, imagePath, url, price, orderNum, orderId, 1));
		Future<String> wxFuture = taskExecutor.submit(() -> appPayProcess(rootPath, imagePath, url, price, orderNum, orderId, 0));
		Map<String, String> map = new HashMap<>();
		map.put("aliUrl", aliFuture.get());
		map.put("wxUrl", wxFuture.get());
		return map;
	}

	/**
	 * 1.支付订单编号和订单id 2.订单二维码生成 3.派单
	 * 
	 * @throws Exception
	 */
	@Override
	public void payNotify(String orderNum, String openId, String attach, String transaction_id, Integer payway) throws Exception {
		if (attach == null) {
			return;
		}
		Long orderId = Long.valueOf(attach);
		OrderDto orderDto = orderFacade.simpleDetailOrder(orderId);
		if(null == orderDto){
			errorComponent.paramReson(orderId, orderNum, transaction_id);
			return;
		}
		orderFacade.updateOrder(orderDto.payState(0).payWay(payway)); // 修改支付状态
		payMapper.insertSelective(new Pay(orderId, transaction_id, orderNum, DateUtils.getCurDttStr()));// 记录支付单号
		String newOrderCode = orderFacade.newOrderCode(orderDto);// 生成二维码
		if (newOrderCode == null) {
			errorComponent.codeReson(orderId, orderNum, transaction_id);
			return;
		}
		Dispatch dispatch = dispatchMapper.selectByPrimaryKey(1);//是否自动派单
		Boolean auto = null == dispatch ? false : dispatch.getDisAuto();
		if (auto) { // true 1代表自动 false 0代表手动
			log.info("自动还是手动:{}" , auto);
			Integer newWaybill = waybillFacade.newWaybill(orderDto.openId(openId));// 派单
			if (newWaybill == null || newWaybill.equals(-1)) {// -1为newWayBILL方法内部返参代表有错误发生
				errorComponent.waybillReson(orderId, orderNum, transaction_id);// 加入到异常单的处理
			}
		} else {
			orderComponent.setAutoComple(orderId);
		}
		taskExecutor.submit(()->achievedService.add(orderId));//自动确认
	}
}
